package com.modules.controller.sys;

import cn.hutool.core.util.StrUtil;
import com.common.constant.LoggerConstant;
import com.common.controller.BaseController;
import com.common.util.ImageUtil;
import com.common.vo.Result;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;


/**
 * 文件上传
 * @author yyq
 *
 */
@Controller
@RequestMapping("/upload")
public class FileController extends BaseController<Object>{

	private final Logger logger = LoggerFactory.getLogger(FileController.class);

	private static final String SUCCESS_MSG = "上传成功";
	private static final String FAIL_MSG = "上传失败";


	/**
	 * 临时文件上传（不压缩）
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("/tempFile")
	public Result<?> tempFile(HttpServletRequest request){
		String fileName = request.getParameter("fileName");
		String path = ImageUtil.NGINXPATH + "/upload/" + getUser().getLastOid() + "/temp/";
		FileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload su = new ServletFileUpload(factory);
		List<FileItem> items = null;
		StringBuffer sb = new StringBuffer();
		try {
			items = su.parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			boolean state=false;
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					try {
						state = true;
						String yName = item.getName();
						String hz = yName.substring(yName.lastIndexOf("."));
						if (StrUtil.isEmpty(fileName)) {
							fileName = System.currentTimeMillis() + hz;
						}
						ImageUtil.processUploadFile(item, path, fileName);
						sb.append("upload/" + getUser().getLastOid() + "/temp/" + fileName);
					} catch (Exception e) {
						state = false;
					}
				}
			}
			if (state) {
				return Result.success(sb.toString(), SUCCESS_MSG);
			}else{
				return Result.fail(FAIL_MSG);
			}
		} catch (FileUploadException e) {
			logger.error(LoggerConstant.ERROR_MSG, e);
			return Result.error();
		}
	}

	/**
	 * 临时照片上传（带压缩）
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("/tempImage")
	public Result<?> tempImage(HttpServletRequest request){
		String fileName = request.getParameter("fileName");
		String path = ImageUtil.NGINXPATH + "/upload/" + getUser().getLastOid() + "/temp/";
		FileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload su = new ServletFileUpload(factory);
		List<FileItem> items = null;
		StringBuffer sb = new StringBuffer();
		try {
			items = su.parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			boolean state=false;
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					try {
						state = true;
						String yName = item.getName();
						String hz = yName.substring(yName.lastIndexOf("."));
						if (StrUtil.isEmpty(fileName)) {
							fileName = System.currentTimeMillis() + hz;
						}
						ImageUtil.processUploadFileGenerateSmall(item, path, fileName);
						sb.append("upload/" + getUser().getLastOid() + "/temp/" + fileName);
					} catch (Exception e) {
						state = false;
					}
				}
			}
			if (state) {
				return Result.success(sb.toString(), SUCCESS_MSG);
			}else{
				return Result.fail(FAIL_MSG);
			}
		} catch (FileUploadException e) {
			logger.error(LoggerConstant.ERROR_MSG, e);
			return Result.error();
		}
	}



	

}
